<?php

namespace App\Http\Controllers\Backend\Setting;

use App\Http\Requests\Backend\Setting\SourceIndexRequest;
use App\Http\Requests\Backend\Setting\SourceStoreRequest;
use App\Http\Requests\Backend\Setting\SourceUpdateRequest;
use App\Models\SettingSource;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Psy\Util\Str;

class SourceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:backend');
    }

    /**
     * Description:渠道列表
     * Author: Sam
     * DateTime: 2019-01-31 14:07
     * @param SourceIndexRequest $request
     * @return mixed
     */
    public function index(SourceIndexRequest $request)
    {
        $page_size = $request->get('page_size',null);
        $channel = $request->get('old',null);
        $type = $request->get('type',null);
        $SettingSource = new SettingSource();
        $SettingSource->setConnection('backend');
        $build = $SettingSource->whereRaw('1=1');
        if($channel !== null){
            $build->where('old', $channel);
        }
        if($type){
            $build->where('type', $type);
        }
        $list = $page_size?$build->paginate($page_size):$build->get();
        return success($list);
    }

    /**
     * Description:添加渠道
     * Author: Sam
     * DateTime: 2019-01-31 14:14
     * @param SourceStoreRequest $request
     * @return mixed
     */
    public function store(SourceStoreRequest $request)
    {
        $params = $this->extractInputFromRules($request,$request->rules());
        if(isset($params['old']) && $params['old'] != SettingSource::H5_TYPE_LLOGIN){
            // 渠道h5
            $params['web_path'] = config('common.h5_domain')."/source/{$params['source_id']}/type/{$params['type']}/index.html";
        }
        SettingSource::create($params);
        return success([]);
    }

    /**
     * Description:获取单个渠道号信息
     * Author: Sam
     * DateTime: 2019-01-31 14:16
     * @param SettingSource $source
     * @return mixed
     */
    public function show(SettingSource $source)
    {
        return success($source);
    }


    /**
     * Description:修改渠道
     * Author: Sam
     * DateTime: 2019-01-31 14:23
     * @param SourceUpdateRequest $request
     * @param SettingSource $source
     * @return mixed
     */
    public function update(SourceUpdateRequest $request, SettingSource $source)
    {
        $params = $this->extractInputFromRules($request,$request->rules());
        $source->updateLogic($params);
        return success([]);
    }

    /**
     * Description:删除渠道
     * Author: Sam
     * DateTime: 2019-01-31 14:25
     * @param SettingSource $source
     * @return mixed
     * @throws \Exception
     */
    public function destroy(SettingSource $source)
    {
        $source->delete();
        return success([]);
    }
}
